const express = require("express");
const mysql = require("mysql");
const jwt = require("jsonwebtoken");
const { expressjwt } = require("express-jwt");

const app = express();

// jwt配置信息
const config = {
  // 加密和解密 token 的密钥
  jwtSecretKey: "houpu No1. ^_^",
  // token 有效期
  expiresIn: "1m",
};

// 解析post请求参数的中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 使用jwt解析中间件
app.use(
  expressjwt({
    secret: config.jwtSecretKey, // 加密时使用的秘钥
    algorithms: ["HS256"], // 算法
  }).unless({
    // 排除指定的接口，不做鉴权
    path: ["/login", "/register"],
  })
);

app.use((err, req, res, next) => {
  if (err.name === "UnauthorizedError") {
    return res.send({ code: err.status, msg: "无效的token" });
  }
});

// 连接数据库
const db = mysql.createPool({
  host: "127.0.0.1",
  user: "root",
  password: "root",
  database: "nodetest",
});

// 登录
app.post("/login", (req, res) => {
  // console.log(req.body)
  db.query(
    `select * from user where name=? and password=?`,
    [req.body.name, req.body.password],
    (err, result) => {
      if (err) return res.send({ code: 9999, msg: err });
      if (result.length === 0) {
        // 用户名或密码错误
        res.send({ code: 8888, msg: "用户名或密码错误" });
      } else {
        // 登录成功
        // console.log(result)
        const user = {
          ...result[0],
          password: "",
        };
        const toKenStr = jwt.sign(user, config.jwtSecretKey, {
          expiresIn: config.expiresIn,
        });
        res.send({
          code: 0,
          msg: "登录成功",
          data: {
            ...user,
            toKen: "Bearer" + toKenStr,
          },
        });
      }
    }
  );
});

// 注册
app.post("/register", (req, res) => {
  // 先查询数据库中是否已有此用户
  db.query(
    "select * from user WHERE name = ?",
    [req.body.name],
    (err, result) => {
      if (err) {
        // 执行异常
        return res.send({ code: 9999, msg: err, data: null });
      }

      if (result.length > 0) {
        // 用户已存在
        return res.send({ code: 4000, msg: "用户已存在" });
      } else {
        // 插入新用户
        db.query(
          "insert into user (name, password) values (?, ?)",
          [req.body.name, req.body.password],
          (err, insertResult) => {
            if (err) return res.send({ code: 9999, msg: err }); // 插入异常

            if (insertResult.affectedRows > 0) {
              // 添加成功
              return res.send({ code: 0, msg: "添加成功" });
            } else {
              // 添加失败
              return res.send({ code: 5000, msg: "添加失败" });
            }
          }
        );
      }
    }
  );
});

app.listen(3000, "127.0.0.1", (err) => {
  console.log("服务器启动");
});
